package com.shuwen.gcdj.service.basics;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuwen.gcdj.bean.DictResp;
import com.shuwen.gcdj.bean.basicsEquitment.response.FileDictResp;
import com.shuwen.gcdj.bean.basicsMaintenance.request.*;
import com.shuwen.gcdj.bean.basicsMaintenance.response.*;
import com.shuwen.gcdj.bean.basicsRepair.request.RepairAddReq;
import com.shuwen.gcdj.bean.basicsRepair.response.RepairListResp;
import com.shuwen.gcdj.bean.dept.response.DeptListItemResp;
import com.shuwen.gcdj.bean.member.response.UserListItemResp;
import com.shuwen.gcdj.bean.structure.response.InspectionItemTemplateResp;
import com.shuwen.gcdj.bean.structure.response.StrategyInspectionItemResp;
import com.shuwen.gcdj.bean.sysDictionary.request.SysDictionaryReq;
import com.shuwen.gcdj.bean.sysDictionary.response.SysDictionaryResp;
import com.shuwen.gcdj.common.api.CommonPage;
import com.shuwen.gcdj.common.api.CommonResult;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.util.BeanHelper;
import com.shuwen.gcdj.dto.account.InitUserDto;
import com.shuwen.gcdj.entity.Account;
import com.shuwen.gcdj.entity.StrategyInspectionitem;
import com.shuwen.gcdj.entity.StrategyInspectionitemtemplaterel;
import com.shuwen.gcdj.entity.SysDictionary;
import com.shuwen.gcdj.entity.basics.*;
import com.shuwen.gcdj.mapper.mysql.*;
import com.shuwen.gcdj.mapper.mysql.basics.*;
import com.shuwen.gcdj.mapper.mysql.sysDictionary.SysDictionaryMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@AllArgsConstructor
public class MaintenanceService extends MethodFactory {

    private final OrderMaintenanceorderdetailMapper orderMaintenanceorderdetailMapper;
    private final OrderMaintenanceorderflowMapper orderMaintenanceorderflowMapper;
    private final OrderMaintenanceorderinspectionitemsaveMapper orderMaintenanceorderinspectionitemsaveMapper;
    private final OrderMaintenanceorderMapper orderMaintenanceorderMapper;
    private final OrderMaintenanceorderstructureimagesaveMapper orderMaintenanceorderstructureimagesaveMapper;
    private final BasicsEquipmentMapper basicsEquipmentMapper;
    private final BasicsStructureMapper basicsStructureMapper;
    private final OrderRepairorderflowMapper orderRepairorderflowMapper;
    private final StrategyInspectionitemMapper strategyInspectionitemMapper;
    private final SysDictionaryMapper sysDictionaryMapper;
    private final StrategyInspectionitemtemplateMapper strategyInspectionitemtemplateMapper;
    private final StrategyInspectionitemtemplaterelMapper strategyInspectionitemtemplateRelMapper;
    private final OrderRepairworkorderMapper orderRepairworkorderMapper;
    private final AccountMapper accountMapper;
    private final DepartmentMapper departmentMapper;
    private final BasicsResourceMapper basicsResourceMapper;
    @Autowired
    private RepairsService reairsService;

    /**
     * 维保列表
     */
    public CommonResult<CommonPage<OrderMainResp>> getMainTen(OrderListReq req) {
        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
        dictionaryReq.setParentCode(Constants.ORDER_MAINTENANCEORDERDETAIL_STATE);
        dictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> dictionary = sysDictionaryMapper.getList(dictionaryReq);
        //部门
        List<DeptListItemResp> department = departmentMapper.getAllList();
        //专业
        SysDictionaryReq dictionaryReqMajor = new SysDictionaryReq();
        dictionaryReqMajor.setParentCode(Constants.ORDER_MAINTENANCEORDERDETAIL_MAJOR);
        dictionaryReqMajor.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> majors = sysDictionaryMapper.getList(dictionaryReqMajor);
        //位置
        SysDictionaryReq areaLocation = new SysDictionaryReq();
        areaLocation.setParentCode(Constants.BASICS_EQUIPMENT_AREA_LOCATION);
        areaLocation.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> areaLocations = sysDictionaryMapper.getList(areaLocation);
        //维保类型
        SysDictionaryReq maintenanceType = new SysDictionaryReq();
        maintenanceType.setParentCode(Constants.MAINTAIN_TYPE);
        maintenanceType.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> dictionaryMapperList = sysDictionaryMapper.getList(maintenanceType);
        //设备
        List<BasicsEquipment> equipments = basicsEquipmentMapper.selectList(
                new QueryWrapper<BasicsEquipment>()
                        .lambda()
                        .eq(BasicsEquipment::getIsDelete, Constants.IS_DELETE_NORMAL));
        Page<OrderMainResp> page = new Page<>(req.getPageNum(), req.getPageSize(), true);
        IPage<OrderMainResp> orderMaintenanceorderMapperList = orderMaintenanceorderMapper.getList(page, req);
        List<OrderMainResp> records = orderMaintenanceorderMapperList.getRecords();
        List<String> userids = records.stream().map(OrderMainResp::getResponsibleUserid).distinct().collect(Collectors.toList());
        List<String> repairCodes = records.stream().map(OrderMainResp::getRepairCode).distinct().collect(Collectors.toList());
        List<UserListItemResp> users = accountMapper.getPowersByUserIds(userids);
        //去null
        repairCodes.removeAll(Collections.singleton(null));
        List<RepairListResp> repairList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(repairCodes)) {
            //报修code查询报修工
            repairList = orderRepairworkorderMapper.getrepairCodesList(repairCodes);
        }
        for (OrderMainResp orderMainResp : records) {
            SysDictionaryResp sysDictionaryResp = dictionary.stream().filter(x -> x.getValue().equals(orderMainResp.getState())).findFirst().orElse(new SysDictionaryResp());
            DeptListItemResp deptListItemResp = department.stream().filter(x -> x.getId().equals(orderMainResp.getResponsibleDepartment())).findFirst().orElse(new DeptListItemResp());
            SysDictionaryResp dictionaryResp = majors.stream().filter(x -> x.getValue().equals(orderMainResp.getMajor())).findFirst().orElse(new SysDictionaryResp());
            SysDictionaryResp orElse = dictionaryMapperList.stream().filter(x -> x.getValue().equals(orderMainResp.getType())).findFirst().orElse(new SysDictionaryResp());
            BasicsEquipment basicsEquipment = equipments.stream().filter(x -> x.getId().equals(orderMainResp.getEquipmentId())).findFirst().orElse(new BasicsEquipment());
            SysDictionaryResp ar = areaLocations.stream().filter(x -> x.getValue().equals(basicsEquipment.getAreaLocation())).findFirst().orElse(new SysDictionaryResp());
            UserListItemResp user = users.stream().filter(x -> x.getId().equals(orderMainResp.getResponsibleUserid())).findFirst().orElse(new UserListItemResp());
            RepairListResp repair = repairList.stream().filter(x -> x.getOrderCode().equals(orderMainResp.getRepairCode())).findFirst().orElse(new RepairListResp());
            orderMainResp.setRepairId(repair.getId());
            orderMainResp.setStateName(sysDictionaryResp.getName());
            orderMainResp.setResponsibleDepartmentName(deptListItemResp.getName());
            orderMainResp.setMajorName(dictionaryResp.getName());
            orderMainResp.setTypeName(orElse.getName());
            orderMainResp.setAreaLocationName(ar.getName());
            orderMainResp.setDepartmentUser(user.getShowName());
            orderMainResp.setEquipmentCode(basicsEquipment.getCode());
        }
        Page<OrderMainResp> resPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resPage.setRecords(records);
        return CommonResult.success(CommonPage.restPage(resPage));
    }

    /**
     * 维保详情
     */
    public CommonResult<List<OrderMainDetailsResp>> getMainTenDetails(String id) {

        List<OrderMaintenanceorderdetail> details = orderMaintenanceorderdetailMapper.selectList(
                new QueryWrapper<OrderMaintenanceorderdetail>().lambda()
                        .eq(OrderMaintenanceorderdetail::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(OrderMaintenanceorderdetail::getSecondStructureId, id));
        List<OrderMainDetailsResp> orderMainDetails = BeanHelper.copyList(details, OrderMainDetailsResp.class);
        for (OrderMainDetailsResp detail : orderMainDetails) {
            StrategyInspectionitem item = strategyInspectionitemMapper.selectById(detail.getInspectionItemId());
            BeanUtils.copyProperties(item, detail);
        }
        return CommonResult.success(orderMainDetails);
    }


    /**
     * 维保详情-策略结构树
     */
    public CommonResult<List<OrderMainChildsResp>> getMainChirden(String id) {

        List<OrderMaintenanceorderdetail> basicsStructures = orderMaintenanceorderdetailMapper.selectList(
                new QueryWrapper<OrderMaintenanceorderdetail>()
                        .lambda()
                        .eq(OrderMaintenanceorderdetail::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(OrderMaintenanceorderdetail::getOrderId, id));
        List<String> stringArrayList = new ArrayList<>();
        //维保检查项预保存
       /* List<OrderMaintenanceorderinspectionitemsave> orderItemModels = orderMaintenanceorderinspectionitemsaveMapper.selectList(
                new QueryWrapper<OrderMaintenanceorderinspectionitemsave>()
                        .lambda()
                        .eq(OrderMaintenanceorderinspectionitemsave::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(OrderMaintenanceorderinspectionitemsave::getOrderId, id));*/
        //二级结构id
        List<String> secondStructureIds = basicsStructures.stream().map(OrderMaintenanceorderdetail::getSecondStructureId)
                .distinct().collect(Collectors.toList());
        //检查项ids
        List<String> itemIds = basicsStructures.stream().map(OrderMaintenanceorderdetail::getInspectionItemId)
                .distinct().collect(Collectors.toList());
        for (OrderMaintenanceorderdetail basicsStructure : basicsStructures) {
            stringArrayList.add(basicsStructure.getFirstStructureId());
        }
        stringArrayList = stringArrayList.stream().distinct().collect(Collectors.toList());
        List<String> finalSetDist = stringArrayList;
        // 一级结构
        List<BasicsStructureResp> firstStructure = basicsStructureMapper.getList(finalSetDist);
        // 二级结构
        List<BasicsStructureResp> secondStructure = basicsStructureMapper.getList(secondStructureIds);
        //检查项数据
        List<StrategyInspectionItemResp> inspectionItemResps = strategyInspectionitemMapper.getListIds(itemIds);
        //检查项关联表模板
        List<StrategyInspectionitemtemplaterel> tempRelModels = strategyInspectionitemtemplateRelMapper.getListAsync(secondStructureIds, itemIds);
        List<String> tempIds = tempRelModels.stream().map(StrategyInspectionitemtemplaterel::getTemplateId).collect(Collectors.toList());
        //检查项模板
        List<InspectionItemTemplateResp> tempModels = strategyInspectionitemtemplateMapper.getListAsync(tempIds);
        //检查项检查结果
        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
        dictionaryReq.setParentCode(Constants.STRATEGY_INSPECTIONITEM_RESULT);
        dictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> resultDictModels = sysDictionaryMapper.getList(dictionaryReq);
        dictionaryReq.setParentCode(Constants.STRATEGY_INSPECTIONITEM_DISPOSAL_METHOD);
        dictionaryReq.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> disposalDictModels = sysDictionaryMapper.getList(dictionaryReq);
        //获取检查项检查结果名称
        for (StrategyInspectionItemResp strategyInspectionItemResp : inspectionItemResps) {
            strategyInspectionItemResp.setInspectionResultText(resultDictModels.stream().filter(sysDictionaryResp -> sysDictionaryResp.getValue().equals(strategyInspectionItemResp.getInspectionResult())).findFirst()
                    .map(SysDictionaryResp::getName).orElse(""));
            strategyInspectionItemResp.setDisposalMethodText(disposalDictModels.stream().filter(x -> x.getValue().equals(strategyInspectionItemResp.getDisposalMethod())).findFirst()
                    .map(SysDictionaryResp::getName).orElse(""));
        }
        List<OrderMainChildsResp> orderMainChildsRespList = BeanHelper.copyList(firstStructure, OrderMainChildsResp.class);
        return CommonResult.success(orderMainChilds(orderMainChildsRespList, secondStructure, basicsStructures, tempRelModels, tempModels, inspectionItemResps, id));
    }


    public List<OrderMainChildsResp> orderMainChilds(List<OrderMainChildsResp> orderMainChildsRespList, List<BasicsStructureResp> secondStructure
            , List<OrderMaintenanceorderdetail> basicsStructures, List<StrategyInspectionitemtemplaterel> tempRelModels
            , List<InspectionItemTemplateResp> tempModels, List<StrategyInspectionItemResp> inspectionItemResps, String id) {
        for (OrderMainChildsResp order : orderMainChildsRespList) {
            List<BasicsStructureResp> structure = secondStructure.stream().filter(basicsStructureResp -> basicsStructureResp.getParentId().equals(order.getId())).collect(Collectors.toList());
            List<OrderMainChildsResp> childs = BeanHelper.copyList(structure, OrderMainChildsResp.class);
            order.setChilds(CollectionUtils.isEmpty(childs) ? new ArrayList() : childs);
            order.setItems(new ArrayList<>());
            for (OrderMainChildsResp child : order.getChilds()) {
                child.childs = new ArrayList<>();
                child.items = new ArrayList<>();
                //一级结构中的二级结构
                List<OrderMaintenanceorderdetail> orderMaintenanceorderdetails = basicsStructures.stream().filter(orderMaintenanceorderdetail -> orderMaintenanceorderdetail.getSecondStructureId().equals(child.getId())).collect(Collectors.toList());
                for (OrderMaintenanceorderdetail maintenanceorderdetail : orderMaintenanceorderdetails) {
                    OrderInspectionItemResp inspectionItemResp = new OrderInspectionItemResp();
                    //模板id
                    String templateId = tempRelModels.stream().filter(te -> te.getInspectionItemId().equals(maintenanceorderdetail.getInspectionItemId())).findFirst().orElse(new StrategyInspectionitemtemplaterel()).getTemplateId();
                    InspectionItemTemplateResp inspectionItemTemp = tempModels.stream().filter(t -> t.getId().equals(templateId)).findFirst().orElse(new InspectionItemTemplateResp());
                    //OrderMaintenanceorderinspectionitemsave itemState = orderItemModels.stream().filter(i -> i.getInspectionItemId().equals(maintenanceorderdetail.getInspectionItemId()) && i.getSecondStructureId().equals(maintenanceorderdetail.getSecondStructureId())).findFirst().orElse(new OrderMaintenanceorderinspectionitemsave());
                    StrategyInspectionItemResp tionItem = inspectionItemResps.stream().filter(t -> t.getId().equals(maintenanceorderdetail.getInspectionItemId())).findFirst().orElse(new StrategyInspectionItemResp());
                    OrderMaintenanceorderdetail basi = basicsStructures.stream().filter(t -> t.getInspectionItemId().equals(maintenanceorderdetail.getInspectionItemId())).findFirst().orElse(new OrderMaintenanceorderdetail());
                    inspectionItemResp.setState(basi.getState());
                    inspectionItemResp.setStrategyId(child.getStrategyId());
                    inspectionItemResp.setStructureId(child.getId());
                    inspectionItemResp.setThreeStructureName(inspectionItemTemp.getStructureName());
                    inspectionItemResp.setDisposalMethod(tionItem.getDisposalMethod());
                    inspectionItemResp.setDisposalMethodText(tionItem.getDisposalMethodText());
                    inspectionItemResp.setInspectionItemId(maintenanceorderdetail.getInspectionItemId());
                    inspectionItemResp.setId(maintenanceorderdetail.getId());
                    inspectionItemResp.setInspectionResult(tionItem.getInspectionResult());
                    inspectionItemResp.setInspectionResultText(tionItem.getInspectionResultText());
                    inspectionItemResp.setItemName(tionItem.getItemName());
                    inspectionItemResp.setOrderId(id);
                    child.items.add(inspectionItemResp);
                }
            }
        }
        return orderMainChildsRespList;
    }


    //根据维保工单获取预存信息
    public CommonResult<List<AnomarlyStructureTreeResp>> getPrestoreMaintrnanceInfo(String orderId) {
        List<AnomarlyStructureTreeResp> anomarlyStructureTreeResps = new ArrayList<>();
        //维保预保存图片结构
        List<OrderMaintenanceorderstructureimagesave> orderStModels = orderMaintenanceorderstructureimagesaveMapper.selectList(
                new QueryWrapper<OrderMaintenanceorderstructureimagesave>()
                        .lambda()
                        .eq(OrderMaintenanceorderstructureimagesave::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(OrderMaintenanceorderstructureimagesave::getOrderId, orderId));
        //维保检查项预保存
        List<OrderMaintenanceorderinspectionitemsave> orderItemModels = orderMaintenanceorderinspectionitemsaveMapper.selectList(
                new QueryWrapper<OrderMaintenanceorderinspectionitemsave>()
                        .lambda()
                        .eq(OrderMaintenanceorderinspectionitemsave::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(OrderMaintenanceorderinspectionitemsave::getOrderId, orderId));
        List<String> firstStructureIds = orderStModels.stream().map(OrderMaintenanceorderstructureimagesave::getFirstStructureId).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(firstStructureIds)) {
            return CommonResult.success(anomarlyStructureTreeResps);
        }
        List<String> imgIds = new ArrayList<>();
        for (OrderMaintenanceorderstructureimagesave data : orderStModels) {
            imgIds.addAll(!StringUtils.isEmpty(data.getImageName())? Arrays.asList(data.getImageName().split(",")):new ArrayList<>());
        }
        //拿取图片
        List<FileDictResp> resource = basicsResourceMapper.getListIds(imgIds);
        // 一级结构
        List<BasicsStructureResp> firstStructure = basicsStructureMapper.getList(firstStructureIds);
        List<String> secondStructureIds = orderStModels.stream().map(OrderMaintenanceorderstructureimagesave::getSecondStructureId).distinct().collect(Collectors.toList());
        // 二级结构
        List<BasicsStructureResp> secondStructure = basicsStructureMapper.getList(secondStructureIds);
        List<String> itemIds = orderItemModels.stream().map(OrderMaintenanceorderinspectionitemsave::getInspectionItemId).distinct().collect(Collectors.toList());
        //检查项数据
        List<StrategyInspectionItemResp> itemModels = strategyInspectionitemMapper.getListIds(itemIds);
        //检查项检查结果
        SysDictionaryReq dic = new SysDictionaryReq();
        dic.setParentCode(Constants.STRATEGY_INSPECTIONITEM_RESULT);
        dic.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> resultDictModels = sysDictionaryMapper.getList(dic);
        //处理方式
        dic.setParentCode(Constants.STRATEGY_INSPECTIONITEM_DISPOSAL_METHOD);
        dic.setState(Constants.SYS_DICTIONARY_STATE_VALID);
        List<SysDictionaryResp> disposalDictModels = sysDictionaryMapper.getList(dic);
        if (CollectionUtils.isEmpty(firstStructure) || CollectionUtils.isEmpty(secondStructure) || CollectionUtils.isEmpty(itemModels)) {
            return CommonResult.success(anomarlyStructureTreeResps);
        }
        for (StrategyInspectionItemResp item : itemModels) {
            item.setInspectionResultText(resultDictModels.stream().filter(dictionaryResp -> dictionaryResp.getValue().equals(item.getInspectionResult())).findFirst()
                    .map(SysDictionaryResp::getName).orElse(""));
            item.setDisposalMethodText(disposalDictModels.stream().filter(sysDictionaryResp -> sysDictionaryResp.getValue().equals(item.getDisposalMethod())).findFirst()
                    .map(SysDictionaryResp::getName).orElse(""));
        }
        return CommonResult.success(anomarlyStructureTreeRespList(itemModels, orderItemModels
                , orderId, firstStructure, secondStructure, orderStModels, resource, anomarlyStructureTreeResps));
    }


    public List<AnomarlyStructureTreeResp> anomarlyStructureTreeRespList(List<StrategyInspectionItemResp> itemModels, List<OrderMaintenanceorderinspectionitemsave> orderItemModels
            , String orderId, List<BasicsStructureResp> firstStructure, List<BasicsStructureResp> secondStructure
            , List<OrderMaintenanceorderstructureimagesave> orderStModels
            , List<FileDictResp> resource, List<AnomarlyStructureTreeResp> anomarlyStructureTreeResps) {

        List<AnomarlyItemResp> checkItemModels = new ArrayList<>();
        for (StrategyInspectionItemResp item : itemModels) {
            AnomarlyItemResp anomarlyItemResp = new AnomarlyItemResp();
            OrderMaintenanceorderinspectionitemsave structure = orderItemModels.stream().filter(orderMaintenanceorderinspectionitemsave -> orderMaintenanceorderinspectionitemsave.getInspectionItemId().equals(item.getId())).findFirst().orElse(new OrderMaintenanceorderinspectionitemsave());
            anomarlyItemResp.setId(item.getId());
            anomarlyItemResp.setOrderId(orderId);
            anomarlyItemResp.setStructureId(structure.getSecondStructureId());
            anomarlyItemResp.setInspectionItemId(item.getId());
            anomarlyItemResp.setItemName(item.getItemName());
            anomarlyItemResp.setInspectionResult(item.getInspectionResult());
            anomarlyItemResp.setInspectionResultText(item.getInspectionResultText());
            anomarlyItemResp.setCheckInspectionResult(structure.getInspectionResult());
            anomarlyItemResp.setDisposalMethod(item.getDisposalMethod());
            anomarlyItemResp.setDisposalMethodText(item.getDisposalMethodText());
            anomarlyItemResp.setCheckDisposalMethod(structure.getDisposalMethod());
            checkItemModels.add(anomarlyItemResp);
        }
        for (BasicsStructureResp item : firstStructure) {
            AnomarlyStructureTreeResp structureTreeResp = new AnomarlyStructureTreeResp();
            //OrderMaintenanceorderinspectionitemsave structure = orderItemModels.stream().filter(x -> x.getInspectionItemId().equals(item.getId())).findFirst().orElse(new OrderMaintenanceorderinspectionitemsave());
            List<BasicsStructureResp> structureResps = secondStructure.stream().filter(basicsStructureResp -> basicsStructureResp.getParentId().equals(item.getId())).collect(Collectors.toList());
            List<AnomarlyStructureTreeResp> anomarlyStructureTree = new ArrayList<>();
            for (BasicsStructureResp basicsStructureResp : structureResps) {
                OrderMaintenanceorderstructureimagesave order = orderStModels.stream().filter(orderMaintenanceorderstructureimagesave -> orderMaintenanceorderstructureimagesave.getSecondStructureId().equals(basicsStructureResp.getId())).findFirst().orElse(new OrderMaintenanceorderstructureimagesave());
                //图片ids
                List<String> imgIds =!StringUtils.isEmpty(order.getImageName())?Arrays.asList(order.getImageName().split(",")):new ArrayList<>();
                List<FileDictResp> imgs = resource.stream().filter(fileDictResp -> imgIds.contains(fileDictResp.getId())).collect(Collectors.toList());
                List<MaintenanceImageResp> imageResps = BeanHelper.copyList(imgs, MaintenanceImageResp.class);
                AnomarlyStructureTreeResp data = new AnomarlyStructureTreeResp();
                data.setId(basicsStructureResp.getId());
                data.setName(basicsStructureResp.getName());
                data.setDepth(basicsStructureResp.getDepth());
                data.setParentId(item.getId());
                data.setOrderId(orderId);
                data.setImages(imageResps);
                data.setRemark(order.getRemark());
                data.setItems(checkItemModels.stream().filter(anomarlyItemResp -> anomarlyItemResp.getStructureId().equals(basicsStructureResp.getId())).collect(Collectors.toList()));
                anomarlyStructureTree.add(data);
            }
            structureTreeResp.setId(item.getId());
            structureTreeResp.setName(item.getName());
            structureTreeResp.setDepth(item.getDepth());
            structureTreeResp.setOrderId(orderId);
            structureTreeResp.setChilds(anomarlyStructureTree);
            anomarlyStructureTreeResps.add(structureTreeResp);
        }
        return anomarlyStructureTreeResps;
    }


    /**
     * 维保详情-预保存
     */
    public CommonResult<Integer> SavePrestoreMaintenanceInfo(OperatePrestoreMaintenanceReq req, InitUserDto dto) {

        int influence = 0;
        if (req.getOrderId().isEmpty() || CollectionUtils.isEmpty(req.getDetailForm())) {
            return CommonResult.validateFailed();
        }
        //获取检查项
        List<String> editIds = req.getDetailForm().stream().map(OperateMaintenanceDetailItemReq::getId).distinct().collect(Collectors.toList());
        //维保详情
        List<OrderMaintenanceorderdetail> detailModels = orderMaintenanceorderdetailMapper.selectList(
                new QueryWrapper<OrderMaintenanceorderdetail>()
                        .lambda()
                        .eq(OrderMaintenanceorderdetail::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(OrderMaintenanceorderdetail::getOrderId, req.getOrderId()));

        List<OrderMaintenanceorderdetail> editDetailModels = detailModels.stream().filter(x -> editIds.contains(x.getId())).collect(Collectors.toList());
        for (OrderMaintenanceorderdetail detail : editDetailModels) {
            detail.setState(req.getDetailForm().stream().filter(x -> x.getId().equals(detail.getId())).findFirst().orElse(new OperateMaintenanceDetailItemReq()).getState());

            influence += detail == null ? 0 : orderMaintenanceorderdetailMapper.updateById(detail);
        }
        //维保预保存图片结构
        List<OrderMaintenanceorderstructureimagesave> oldStModels = orderMaintenanceorderstructureimagesaveMapper.selectList(
                new QueryWrapper<OrderMaintenanceorderstructureimagesave>()
                        .lambda()
                        .eq(OrderMaintenanceorderstructureimagesave::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(OrderMaintenanceorderstructureimagesave::getOrderId, req.getOrderId()));

        //维保检查项预保存
        List<OrderMaintenanceorderinspectionitemsave> olditemModels = orderMaintenanceorderinspectionitemsaveMapper.selectList(
                new QueryWrapper<OrderMaintenanceorderinspectionitemsave>()
                        .lambda()
                        .eq(OrderMaintenanceorderinspectionitemsave::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(OrderMaintenanceorderinspectionitemsave::getOrderId, req.getOrderId()));

        List<String> oldStModelidslIst = oldStModels.stream().map(OrderMaintenanceorderstructureimagesave::getId).collect(Collectors.toList());
        influence += CollectionUtils.isEmpty(oldStModels) ? 0 : orderMaintenanceorderstructureimagesaveMapper.deleteBatchIds(oldStModelidslIst);
        List<String> olditemModelids = olditemModels.stream().map(OrderMaintenanceorderinspectionitemsave::getId).collect(Collectors.toList());
        influence += CollectionUtils.isEmpty(olditemModelids) ? 0 : orderMaintenanceorderinspectionitemsaveMapper.deleteBatchIds(oldStModelidslIst);

        for (OperateAnomalyMaintenanceStructureReq structureReq : req.getAnomalyForm()) {
            OrderMaintenanceorderstructureimagesave imageSaveReq = new OrderMaintenanceorderstructureimagesave();
            imageSaveReq.setOrderId(req.getOrderId());
            imageSaveReq.setFirstStructureId(structureReq.getFirstStructureId());
            imageSaveReq.setSecondStructureId(structureReq.getSecondStructureId());
            imageSaveReq.setImageName(!CollectionUtils.isEmpty(structureReq.getImages()) ? String.join(",", structureReq.getImages()) : null);
            imageSaveReq.setRemark(structureReq.getRemark());
            influence += orderMaintenanceorderstructureimagesaveMapper.insert(imageSaveReq);

            for (OperateAnomalyMaintenanceItemReq item : structureReq.items) {
                OrderMaintenanceorderinspectionitemsave maintenance = new OrderMaintenanceorderinspectionitemsave();
                maintenance.setOrderId(req.getOrderId());
                maintenance.setSecondStructureId(structureReq.getSecondStructureId());
                maintenance.setInspectionItemId(item.getItemId());
                maintenance.setDisposalMethod(item.getCheckDisposalMethodText());
                maintenance.setInspectionResult(item.getCheckInspectionResultText());
                maintenance.setState(true);
                influence += orderMaintenanceorderinspectionitemsaveMapper.insert(maintenance);
            }
        }
        return CommonResult.success(influence);
    }


    //维保保存修改
    public CommonResult<Integer> updataDetailRepairAsync(MaintenanceRepairExamineReq req, InitUserDto initUserDto) {

        int influence = 0;
        List<OrderMaintenanceorderdetail> orderMaintenanceorderdetails = orderMaintenanceorderdetailMapper.selectList(
                new QueryWrapper<OrderMaintenanceorderdetail>()
                        .lambda()
                        .eq(OrderMaintenanceorderdetail::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(OrderMaintenanceorderdetail::getOrderId, req.getOrderId()));
        for (OrderMaintenanceorderdetail data : orderMaintenanceorderdetails) {
            Boolean state = req.getMaintenanceorderdetails().stream().filter(x -> x.getId().equals(data.getId()) && x.getSecondStructureId().equals(data.getSecondStructureId())).findFirst().orElse(new MaintenanceorderdetailReq()).getState();
            data.setState(state);

            influence += data == null ? 0 : orderMaintenanceorderdetailMapper.updateById(data);
        }
        OrderMaintenanceorder orderMaintenanceorder = orderMaintenanceorderMapper.selectOne(
                new QueryWrapper<OrderMaintenanceorder>()
                        .lambda()
                        .eq(OrderMaintenanceorder::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(OrderMaintenanceorder::getId, req.getOrderId()));
        Integer state = req.getMaintenanceorderdetails().stream().map(MaintenanceorderdetailReq::getState).collect(Collectors.toList()).contains(true) ? 3 : 2;
        orderMaintenanceorder.setState(state);
        orderMaintenanceorder.setEndDate(LocalDateTime.now());
        //设备
        BasicsEquipment equipment = basicsEquipmentMapper.selectOne(
                new QueryWrapper<BasicsEquipment>()
                        .lambda()
                        .eq(BasicsEquipment::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(BasicsEquipment::getId, orderMaintenanceorder.getEquipmentId()));

        if (orderMaintenanceorder == null) {
            return CommonResult.validateFailed("工单不存在");
        }
        //保存维保流程
        OrderFlowReq orderFlowReq = new OrderFlowReq();
        orderFlowReq.setEquipmentId(orderMaintenanceorder.getEquipmentId());
        orderFlowReq.setOrderId(req.getOrderId());
        orderFlowReq.setOrderCode(orderMaintenanceorder.getOrderCode());
        orderFlowReq.setEquipmentName(equipment.getName());
        orderFlowReq.setOrderState(Constants.FRP_FLOW_TWO);
        orderFlowReq.setOperatorType(Constants.FRP_FLOW_TWO);
        orderFlowReq.setOperator(initUserDto.getUserId());
        orderFlowReq.setUpdateId(initUserDto.getUserId());
        this.savaOrderFlow(orderFlowReq);
//        OrderRepairworkorderdetail orderdetail = orderRepairworkorderdetailMapper.getFistOrderdetailByCodeDesc();
        if (!CollectionUtils.isEmpty(req.repairDetails)) {
            //保存维保流程新增报修
            OrderFlowReq orderFlowReq1 = new OrderFlowReq();
            orderFlowReq1.setEquipmentId(orderMaintenanceorder.getEquipmentId());
            orderFlowReq1.setOrderId(req.getOrderId());
            orderFlowReq1.setOrderCode(orderMaintenanceorder.getOrderCode());
            orderFlowReq1.setEquipmentName(equipment.getName());
            orderFlowReq1.setOrderState(Constants.FRP_FLOW_TREE);
            orderFlowReq1.setOperatorType(Constants.FRP_FLOW_TREE);
            orderFlowReq1.setOperator(initUserDto.getUserId());
            orderFlowReq1.setUpdateId(initUserDto.getUserId());
            this.savaOrderFlow(orderFlowReq1);
            RepairAddReq repair = new RepairAddReq();
            repair.setAreaLocation(equipment.getAreaLocation());
            repair.setEquipmentId(orderMaintenanceorder.getEquipmentId());
            repair.setMajor(orderMaintenanceorder.getMajor());
            repair.setGrade(1);
            repair.setSoursce(orderMaintenanceorder.getType().equals(Constants.LEVEL_ONE) ? Constants.LEVEL_ONE : Constants.LEVEL_TWO);
            repair.setRepairDepartment(orderMaintenanceorder.getResponsibleDepartment());
            repair.setRepairDetails(req.getRepairDetails());
            String repairCode = reairsService.addRepairs(repair, initUserDto).getData();
            orderMaintenanceorder.setRepairCode(repairCode);
            influence += orderMaintenanceorderMapper.updateById(orderMaintenanceorder);
        }
        influence += orderMaintenanceorderMapper.updateById(orderMaintenanceorder);
        return CommonResult.success(influence);
    }


    /**
     * 维保详情-保存
     */
    public CommonResult<String> submit(OrderMainSubmitReq req, InitUserDto initUserDto) {
        for (OrderFirstReq orderFirstReq : req.getOrderFirstReqs()) {
            for (OrderTwoReq orderTwoReq : orderFirstReq.getOrderTwoReq()) {
                for (OrderTreenReq orderTreenReq : orderTwoReq.getOrderTreenReq()) {
                    OrderMaintenanceorderdetail orderMain = new OrderMaintenanceorderdetail();
                    orderMain.setSecondStructureId(orderTwoReq.getSecondStructureId());
                    BeanUtils.copyProperties(orderTreenReq, orderMain);
                    orderMain.setPicture(orderTreenReq.getImageName());
                    orderMaintenanceorderdetailMapper.insert(orderMain);
                }
            }
        }

        //保存维保流程
        OrderFlowReq orderFlowReq = new OrderFlowReq();
        BeanUtils.copyProperties(req, orderFlowReq);
        orderFlowReq.setOrderState(Constants.FRP_FLOW_TWO);
        orderFlowReq.setOperatorType(Constants.FRP_FLOW_TWO);
        orderFlowReq.setOperator(initUserDto.getUsername());
        orderFlowReq.setOrderId(initUserDto.getUserId());
        orderFlowReq.setUpdateId(initUserDto.getUserId());
        this.savaOrderFlow(orderFlowReq);

        //新增报修流程
        OrderRepairorderflow orderRepairorderflow = new OrderRepairorderflow();
        orderRepairorderflow.setOrderId(req.getOrderId());
        orderRepairorderflow.setOperator(initUserDto.getUserId());
        orderRepairorderflow.setOperatorName(initUserDto.getUsername());
        orderRepairorderflow.setRemark("新增");
        orderRepairorderflowMapper.insert(orderRepairorderflow);
        return CommonResult.success("保存成功");
    }


    /**
     * 维保明细-维保流程查看
     */
    public CommonResult<List<OrderPeopleReq>> getFlow(String id) {
        List<OrderMaintenanceorderflow> orderMaintenanceorderflows = orderMaintenanceorderflowMapper.selectList(
                new QueryWrapper<OrderMaintenanceorderflow>().lambda()
                        .eq(OrderMaintenanceorderflow::getOrderId, id));
        List<OrderPeopleReq> repairPeopleReqs = BeanHelper.copyList(orderMaintenanceorderflows, OrderPeopleReq.class);
        for (OrderPeopleReq orderMaintenanceorderflow : repairPeopleReqs) {
            if (!StringUtils.isEmpty(orderMaintenanceorderflow.getOperator())) {
                Account account = accountMapper.selectById(orderMaintenanceorderflow.getOperator());
                orderMaintenanceorderflow.setOperator(account.getShowName());
            }
            SysDictionary sysDictionaryed = sysDictionaryMapper.selectOne(
                    new QueryWrapper<SysDictionary>().lambda()
                            .eq(SysDictionary::getValue, orderMaintenanceorderflow.getOperatorType())
                            .eq(SysDictionary::getParentCode, "Order_Maintenanceorderflow_OperateType"));
            orderMaintenanceorderflow.setOperatorTypeName(sysDictionaryed.getName());
        }
        return CommonResult.success(repairPeopleReqs.stream().sorted(Comparator.comparing(OrderPeopleReq::getCreateTime)).collect(Collectors.toList()));
    }


    /**
     * 维保明细-维保流程查看
     */
/*    public CommonResult<List<OrderPeopleReq>> getFlow(String id) {

        List<OrderMaintenanceorderflow> orderMaintenanceorderflows = orderMaintenanceorderflowMapper.selectList(
                new QueryWrapper<OrderMaintenanceorderflow>().lambda()
                        .eq(OrderMaintenanceorderflow::getOrderId, id));

        //字典维保操作
        SysDictionaryReq dic = new SysDictionaryReq();
        dic.setParentCode(Constants.Order_Maintenanceorderflow_OperateType);
        List<SysDictionaryResp> resultDictModels = sysDictionaryMapper.GetList(dic);


        List<String>userids=orderMaintenanceorderflows.stream().map(OrderMaintenanceorderflow::getOperator).distinct().collect(Collectors.toList());

        List<UserListItemResp> users=accountMapper.getPowersByUserIds(userids);


        List<OrderPeopleReq> repairPeopleReqs = BeanHelper.copyList(orderMaintenanceorderflows, OrderPeopleReq.class);
        for (OrderPeopleReq orderMaintenanceorderflow : repairPeopleReqs) {
            SysDictionaryResp dict = resultDictModels.stream().filter(x -> x.getValue().equals(orderMaintenanceorderflow.getOperatorType())).findFirst().orElse(new SysDictionaryResp());
            UserListItemResp user=users.stream().filter(x->x.getId().equals(orderMaintenanceorderflow.getOperator())).findFirst().orElse(new UserListItemResp());
            orderMaintenanceorderflow.setOperatePerson(user.getShowName());
            orderMaintenanceorderflow.setOperatorTypeName(dict.getName());
        }
        return CommonResult.success(repairPeopleReqs);
    }*/


    /**
     * 获取工单状态
     */
    public CommonResult<List<DictResp>> getInstallAreas() {
        List<SysDictionary> sysDictionaries = sysDictionaryMapper.selectList(
                new QueryWrapper<SysDictionary>().lambda()
                        .eq(SysDictionary::getParentCode, Constants.ORDER_STATE));
        List<DictResp> dictResps = BeanHelper.copyList(sysDictionaries, DictResp.class);
        return CommonResult.success(dictResps);
    }


    public MaintenanceStatisticsResp getMaintenanceStatistics(String equipmentId) {
        MaintenanceStatisticsResp resp = new MaintenanceStatisticsResp();
        List<OrderMainResp> models = orderMaintenanceorderMapper.getTodayMaintenanceListByEquipmentId(equipmentId);
        //已报修
        Integer alreadyRepair = models.stream().filter(x -> x.getState().equals(3)).collect(Collectors.toList()).size();
        //完成数
        Integer succeed = models.stream().filter(x -> !x.getState().equals(1)).collect(Collectors.toList()).size();
        succeed = Double.isNaN(succeed) ? 0 : succeed;
        //待实施
        Integer treatImplement = models.stream().filter(x -> x.getState().equals(1)).collect(Collectors.toList()).size();
        Integer total = models.size();
        Double rate = total > 0 ? ((double) succeed / (double) total) * 100 : 0;
        resp.setTotal(total);
        resp.setSucceed(Math.toIntExact(Math.round(rate)));
        resp.setAlreadyRepair(alreadyRepair);
        resp.setTreatImplement(treatImplement);
        return resp;
    }
}
